﻿using aier.dataaccess.dapper;
using aier.dataaccess.model;
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aier.business.logic
{
    public partial class CommonBll
    {
        //public SequenceBll sequenceBll { get; set; }

        /// <summary>
        /// 批量创建筛查结果 
        /// 原程序 :ScResultServiceImpl-> updateBatch(List<TScResult> scResults) 
        /// </summary>
        /// <param name="screenResults"></param>
        /// <returns></returns>
        public ResResult MutipleCreateResult(ScreenResultRequest screenResultRequest)
        {
            try
            {
                ResResult resResult = null;
                //创建潜客
                if (screenResultRequest != null && screenResultRequest.screenCustomer != null)
                {
                    Guid? customerGuid = screenResultRequest.screenCustomer.new_customerid;
                    Guid? scid = screenResultRequest.screenCustomer.new_scid;
                    if (customerGuid != null && scid != null)
                    {
                        
                        string customeridStr = customerGuid.ToString();
                        string scidStr = scid.ToString();
                        bool flag = screenCustomerBll.ExistsScreenCustomer(new Guid(customeridStr), new Guid(scidStr));
                        ScreenView screenView = screenBll.FetchScreenByScreenID(new Guid(scidStr));
                        screenResultRequest.screenCustomer.new_screenteamid = screenView.new_screenteamId;
                        screenResultRequest.screenCustomer.new_scstate = 0;
                        if (!flag)
                        {
                            screenResultRequest.screenCustomer.new_scnum = sequenceBll.GetSCNum();
                            resResult = screenCustomerBll.CreateCustomer(screenResultRequest.screenCustomer);
                        }
                    }
                }
                //创建筛查结果
                resResult = screenResultBll.MutipleParallelCreateResult(screenResultRequest.screenResults);
                

                return resResult;
            }
            catch (Exception ex)
            {
                log.Error("ScreenResultBll-> MutipleUpdateResult: " + ex.Message);
                return resResult.FailResult(ex.Message);
            }
        }

        /// <summary>
        /// 创建筛查宣教记录
        /// </summary>
        /// <param name="screen"></param>
        /// <returns></returns>
        public ResResult UpdateScreenEquimentsAssociate(Screen screen)
        {
            //当筛查资源不为空的情况下 会 创建筛查记录并创建与筛查资源的关系
            if (screen.Resources != null && screen.Resources.Length > 0)
            {
                IEnumerable<ScreenEquipmentView> equipments = equipmentDal.QueryCurrentId(screen.Resources);
                return this.UpdateScreenEquimentsAssociate(screen, equipments);
            }
            else
            {
                //没有筛查资源时  则直接跟新筛查记录
                return screenBll.UpdateScreen(screen);
            }
        }


        /// <summary>
        /// 保存宣教信息，更新筛查客户信息
        /// 原程序 ：ScreenInfoServiceImpl-> saveScPreach(DoctorUser user, TScPreach scPreach)
        /// </summary>
        /// <param name="customer">筛查客户</param>
        /// <param name="propaganda">筛查宣教</param>
        /// <returns></returns>
        public ResResult SaveScCustomerPropaganda(ScreenCustomer customer, ScreenPropaganda propaganda)
        {
            resResult = screenPropagandaBll.CreatePropaganda(propaganda);

            if (resResult.ResultState == 1)
            {
                customer.new_scstate = 1;
                resResult = screenCustomerBll.UpdateScreenCustomer(customer);
            }

            return resResult;

        }

        /// <summary>
        /// 保存宣教信息，更新筛查客户，潜客信息
        /// 原程序 ：ScreenInfoServiceImpl-> Result saveScPreach(DoctorUser user, TScPreach scPreach, String sc_customerid, Short insurancetype, Short insurancelocation,String remark)
        /// </summary>
        /// <param name="new_sc_customerid">筛查客户ID</param>
        /// <param name="lead">潜客</param>
        /// <param name="propaganda">宣教</param>
        /// <returns></returns>
        public ResResult SaveScLeadPropaganda(Guid new_sc_customerid, LeadInfo lead, ScreenPropaganda propaganda)
        {
            try
            {
                //1、创建宣教
                ScreenView screenView = screenBll.FetchScreenByScreenID(propaganda.new_screen.Value);
                propaganda.OwnerId = screenView.OwnerId;
                propaganda.new_doctor = propaganda.userid;
                resResult = screenPropagandaBll.CreatePropaganda(propaganda);

                //2、更新个人筛查状态为已完成
                ScreenCustomer customer = new ScreenCustomer();
                customer.new_scstate = 1;
                customer.OwnerId = screenView.OwnerId;
                customer.new_scid = propaganda.new_screen;
                customer.new_customerid = propaganda.new_lead;
                customer.new_sc_customerid = new_sc_customerid;
                screenCustomerBll.UpdateScreenCustomer(customer);

                //3、更新潜客信息
                lead.ownerid = screenView.OwnerId;
                lead.leadid = propaganda.new_lead.Value;
                leadBll.UpdateLeadBase(lead);

                return resResult.SuccessResult("CommonBll-> SaveScLeadPropaganda :" + resResult.Result);
            }
            catch (Exception ex)
            {
                return resResult.FailResult("CommonBll-> SaveScLeadPropaganda :" + ex.Message);
            }

        }

        /// <summary>
        /// 创建筛查宣教记录
        /// </summary>
        /// <param name="screen"></param>
        /// <returns></returns>
        public ResResult CreateScreenEquimentsAssociate(Screen screen)
        {
            //当筛查资源不为空的情况下 会 创建筛查记录并创建与筛查资源的关系
            if (screen.Resources != null && screen.Resources.Length > 0)
            {
                IEnumerable<ScreenEquipmentView> equipments = equipmentDal.QueryCurrentId(screen.Resources);
                return this.CreateScreenEquimentsAssociate(screen, equipments);
            }
            else
            {
                //没有筛查资源时  则直接创建筛查记录
                return screenBll.CreateScreen(screen);
                //return resResult.FailResult("资源设备没有赋值");
            }
        }


        /// <summary>
        /// 创建筛查、筛查设备关系
        /// 原程序 :ScreenInfoServiceImpl-> addScreenInfo(ScreenInfo4WS screenInfo4WS, DoctorUser doctorUser) 
        /// </summary>
        /// <param name="screen">筛查对像</param>
        /// <param name="equipments">筛查设备关系</param>
        /// <returns></returns>
        public ResResult CreateScreenEquimentsAssociate(Screen screen, IEnumerable<ScreenEquipmentView> equipments)
        {
            try
            {
                //1、创建筛查对像
                ResResult result = screenBll.CreateScreen(screen);
                EntityReference screenReference = new EntityReference("new_screen", result.Result);

                //2、准备关系
                List<EntityReference> equipmentReferences = new List<EntityReference>();
                foreach (ScreenEquipmentView itemview in equipments)
                {
                    equipmentReferences.Add(new EntityReference("new_equipment", itemview.new_equipmentid));
                }

                //3、创建关系
                commonWcf.ExceAisassociateMToMEntities(screenReference, equipmentReferences, "new_new_screen_new_equipment");

                return result;
            }
            catch (Exception ex)
            {
                log.Error("CommonBll-> CreateScreenEquimentsAssociate :" + ex.Message);
                return resResult.FailResult("CommonBll-> CreateScreenEquimentsAssociate :" + ex.Message);
            }
        }



        /// <summary>
        /// 更新筛查、筛查设备关系
        /// 原程序 :ScreenInfoServiceImpl-> modScreenInfo(ScreenInfo4WS screenInfo4WS, DoctorUser doctorUser) 
        /// </summary>
        /// <param name="screen">筛查对像</param>
        /// <param name="equipments">筛查设备关系</param>
        /// <returns></returns>
        public ResResult UpdateScreenEquimentsAssociate(Screen screen, IEnumerable<ScreenEquipmentView> equipments)
        {
            try
            {
                //1、更新筛查对像
                ResResult result = screenBll.UpdateScreen(screen);
                EntityReference screenReference = new EntityReference("new_screen", screen.new_screenId);

                //2、准备解除关系
                List<EntityReference> delreferences = new List<EntityReference>();
                IEnumerable<ScreenEquipmentView> view1 = screenEquipmentBll.QueryScreenEquipmentViewByScreenId(screen.new_screenId);
                foreach (ScreenEquipmentView itemview in view1)
                {
                    delreferences.Add(new EntityReference("new_equipment", itemview.new_equipmentid));
                }

                //3、准备重新创建关系
                List<EntityReference> addreferences = new List<EntityReference>();
                foreach (ScreenEquipmentView itemview in equipments)
                {
                    addreferences.Add(new EntityReference("new_equipment", itemview.new_equipmentid));
                }

                //4、解除关系
                commonWcf.ExceDisassociate(screenReference, delreferences, "new_new_screen_new_equipment");

                //5、创建关系
                commonWcf.ExceAisassociateMToMEntities(screenReference, addreferences, "new_new_screen_new_equipment");

                return resResult.SuccessResult("CommonBll-> UpdateScreenEquimentsAssociate :" + resResult.Result);
            }
            catch (Exception ex)
            {
                log.Error("CommonBll-> UpdateScreenEquimentsAssociate :" + ex.Message);
                return resResult.FailResult("CommonBll-> UpdateScreenEquimentsAssociate :" + ex.Message);
            }
        }

        /// <summary>
        /// 保存筛查客户
        /// 团队模式信息采集
        /// 如果leadid为空表示需要新增客户,否则为更新客户
        /// 原程序 ： public Result saveScCustomer(DoctorUser user, TLeadBase lead, String scid, String teamid)
        /// 页面组对像时需要注意:
        /// 1、创建潜客时，new_inputingtime(建档时间), new_phone(手机号), new_brithdatenew(出生日期), new_datasource(根据来源选择选项集)赋值
        /// 2、预约表创建时  new_datasource(根据来源选择选项集)
        /// </summary>
        /// <param name="lead">潜客对像</param>
        /// <param name="scid">筛查ID</param>
        /// <param name="teamid">筛查组ID</param>
        /// <returns></returns>
        public ResResult SaveScreenCustomer(LeadInfo lead, Guid? scid, Guid? teamid, Guid? scitemid)
        {
            try
            {
                ScreenView screen = screenBll.FetchScreenByScreenID(scid.HasValue?scid.Value:Guid.Empty);
                lead.ownerid = screen.OwnerId;
                if (screen.new_screenteamId.HasValue)
                    teamid = screen.new_screenteamId;
                //1、创建或更新潜客
                if (Guid.Empty.Equals(lead.leadid))
                {
                    resResult = leadBll.SaveLeadInfo(lead);
                }
                else
                {
                    resResult = leadBll.UpdateLeadBase(lead);
                    resResult.Result = lead.leadid;
                }

                log.Info("resResult.Result:" + resResult.Result);
                //2、创建筛查客户
                ScreenCustomer customer = new ScreenCustomer();
                customer.new_scstate = 0;
                customer.new_scid = scid;
                //customer.userid = lead.userid;
                customer.OwnerId = lead.ownerid;
                customer.new_screenteamid = teamid;
                customer.new_customerid = resResult.Result;
                customer.new_scitemid = scitemid;
                customer.new_scnum = sequenceBll.GetSCNum();
                ResResult customerResult = screenCustomerBll.CreateCustomer(customer);
                //log.Info("customerResult:" + customerResult.SuccessResult.resul)

                //3、返回潜客ID与筛查客户ID
                List<Guid> resultIds = new List<Guid>();
                Guid leadid = Guid.Empty;
                Guid customerid = Guid.Empty;
                if (resResult != null 
                    && !CommonUtil.isDynamicNull(resResult.Result)
                    && Guid.TryParse(resResult.Result.ToString(), out leadid))
                {
                    resultIds.Add(leadid);
                }
                if (customerResult != null 
                    && !CommonUtil.isDynamicNull(customerResult.Result)
                    && Guid.TryParse(customerResult.Result.ToString(), out customerid))
                {
                    resultIds.Add(customerid);
                }
                resResult.Result = String.Join("|", resultIds.ToArray());


                return resResult.SuccessResult("CommonBll-> SaveScreenCustomer :" + resResult.Result);
            }
            catch (Exception ex)
            {
                log.Error("CommonBll-> SaveScreenCustomer :" + ex.Message);
                return resResult.FailResult("CommonBll-> SaveScreenCustomer :" + ex.Message);
            }
        }


        public ResResult UpdateScreenCustomer(LeadInfo lead, ScreenCustomer customer)
        {
            lead.new_patientsource = 3;


            resResult = leadBll.UpdateLeadBase(lead);

            ResResult customerResult = screenCustomerBll.UpdateScreenCustomer(customer);
            return null;
        }


        /// <summary>
        /// 校园筛查单人模式修改
        /// 原程序 ：modXYSC(DoctorUser user, TLeadBase tLeadBase, TScCustomer tScCustomer, List<TScResult> insertResults, List<TScResult> modifyResults, TScPreach tScPreach, ReservationInfo reservationInfo)
        /// </summary>
        /// <param name="scobj"></param>
        /// <returns></returns>
        public ResResult UpdateXYSC(SCOBJ scobj)
        {
            try
            {
                //1、更新备注信息到潜客
                LeadInfo lead = scobj.lead;
                leadBll.UpdateLeadBase(lead);

                //2、新增筛查客户数据
                if (screenCustomerBll.ExistsScreenCustomer(lead.leadid, scobj.customer.new_scid.Value))
                {
                    ScreenCustomer customer = scobj.customer;
                    customer.new_scstate = 1;
                    resResult = screenCustomerBll.UpdateScreenCustomer(customer);
                }
                else
                {
                    ScreenCustomer customer = scobj.customer;
                    customer.new_scstate = 1;
                    customer.new_scnum = sequenceBll.GetSCNum();
                    customer.OwnerId = scobj.propaganda.new_followdoctor.Value;
                    resResult = screenCustomerBll.CreateCustomer(customer);
                }

                //3、保存筛查结果
                if (scobj.CreateResults != null && scobj.CreateResults.Count() > 0)
                {
                    IEnumerable<ScreenResult> createResults = scobj.CreateResults;
                    resResult = screenResultBll.MutipleCreateResult(createResults);
                }

                if (scobj.UpdateResults != null && scobj.UpdateResults.Count() > 0)
                {
                    IEnumerable<ScreenResult> updateResults = scobj.UpdateResults;
                    resResult = screenResultBll.MutipleUpdateResult(updateResults);
                }

                //4、创建预约
                if (scobj.propaganda.new_isorder.Value && resResult.ResultState == 1)
                {
                    Reservation reservation = scobj.reservation;
                    resResult = reservationBll.CreateReservation(reservation);
                }

                return resResult.SuccessResult("CommonBll-> UpdateXYSC 成功");
            }
            catch (Exception ex)
            {
                log.Error("CommonBll-> UpdateXYSC :" + ex.Message);
                return resResult.FailResult("CommonBll-> UpdateXYSC :" + ex.Message);
            }

        }

        /// <summary>
        /// 校园查单人模式录入
        /// 原程序 ：ScreenInfoServiceImpl-> addXYSC(DoctorUser user, TLeadBase tLeadBase, TScCustomer tScCustomer, List<TScResult> tScResults, TScPreach tScPreach, ReservationInfo reservationInfo)
        /// </summary>
        /// <param name="scobj"></param>
        /// <returns></returns>
        public ResResult CreateXYSC(SCOBJ scobj)
        {
            try
            {
                //1、更新备注信息到潜客
                LeadInfo lead = scobj.lead;
                leadBll.UpdateLeadBase(lead);

                //2、新增筛查客户数据
                if (!screenCustomerBll.ExistsScreenCustomer(lead.leadid, scobj.customer.new_scid.Value))
                {
                    ScreenCustomer customer = scobj.customer;
                    customer.new_scstate = 1;
                    customer.new_scnum = sequenceBll.GetSCNum();
                    customer.new_school = lead.new_school;
                    customer.new_scitemid = scobj.screen.new_new_screenitem;
                    customer.new_screenteamid = scobj.screen.new_screenteamId;
                    customer.new_scid = scobj.screen.new_screenId;

                    resResult = screenCustomerBll.CreateCustomer(customer);
                }

                //3、保存筛查结果
                if (scobj.CreateResults != null && scobj.CreateResults.Count() > 0 && resResult.ResultState == 1)
                {
                    IEnumerable<ScreenResult> results = scobj.CreateResults;
                    resResult = screenResultBll.MutipleCreateResult(results);
                }

                //4、创建宣讲
                ScreenPropaganda propaganda = scobj.propaganda;
                if (resResult.ResultState == 1)
                {
                    resResult = screenPropagandaBll.CreatePropaganda(propaganda);
                }

                //5、创建预约
                if (propaganda.new_isorder.Value && resResult.ResultState == 1)
                {
                    Reservation reservation = scobj.reservation;
                    resResult = reservationBll.CreateReservation(reservation);
                }
                return resResult.SuccessResult("CommonBll-> CreateXYSC 成功");
            }
            catch (Exception ex)
            {
                log.Error("CommonBll-> CreateXYSC :" + ex.Message);
                return resResult.FailResult("CommonBll-> CreateXYSC :" + ex.Message);
            }

        }


        /// <summary>
        /// 社区筛查单人模式修改
        /// 原程序 ：ScreenInfoServiceImpl-> modSQSC(DoctorUser user, TLeadBase tLeadBase, TScCustomer tScCustomer, List<TScResult> insertResults, List<TScResult> modifyResults, TScPreach tScPreach, ReservationInfo reservationInfo)
        /// </summary>
        /// <param name="sqsc">社区筛查单人模式对像</param>
        /// <returns></returns>
        public ResResult UpdateSQSC(SCOBJ sqsc)
        {
            try
            {
                //1、更新潜客
                LeadInfo lead = sqsc.lead;
                //lead.new_patientsource = 3;
                resResult = leadBll.UpdateLeadBase(lead);

                //2、先删除筛查结果
                ScreenCustomer customer = sqsc.customer;
                resResult = screenCustomerBll.UpdateScreenCustomer(customer);
                bool result = screenResultBll.DeleteScreenResult(customer.new_customerid.Value, customer.new_scid.Value);

                //3、创建筛查结果
                IEnumerable<ScreenResult> createResult = sqsc.CreateResults;
                if (result && createResult != null && createResult.Count() > 0)
                {
                    foreach (var sr in createResult)
                    {
                        sr.new_scid = customer.new_scid;
                        sr.new_customerid = customer.new_customerid;
                    }

                    resResult = screenResultBll.MutipleCreateResult(createResult);
                }

                //4、创建或更新预约
                if (resResult.ResultState == 1 && sqsc.reservation != null)
                {
                    Reservation reservation = sqsc.reservation;
                    //if (reservation.new_reservationid != null&&Guid.Parse(reservation.new_reservationid.ToString())!=Guid.Empty)
                    //{                      
                    //    reservationBll.UpdateReservationDate(reservation);
                    //}
                    //else
                    //{
                    reservation.new_lead = lead.leadid;
                    reservation.new_screen = customer.new_scid;
                    if (reservation.new_reservationdate != null && reservation.new_hospital != null && reservation.new_department != null)
                    {
                        reservation.new_isreview = true;
                        DateTime startDate = reservation.new_reservationdate.Value.ToUniversalTime();
                        DateTime endDate = Convert.ToDateTime(reservation.new_reservationdate.Value.ToString("yyyy-MM-dd 15:59:59"));
                        int IsExistsReservation = reservationBll.QueryReservationBy(customer.new_customerid.Value, startDate, endDate, reservation.new_hospital.Value, reservation.new_department.Value);
                        if (IsExistsReservation == 0)
                            reservationBll.CreateReservation(reservation);
                    }
                    //}
                }

                return resResult.SuccessResult("CommonBll->UpdateSQSC : 成功");
            }
            catch (Exception ex)
            {
                log.Error("CommonBll-> UpdateSQSC :" + ex.Message);
                return resResult.FailResult("CommonBll-> UpdateSQSC :" + ex.Message);
            }
        }

        public ResResult UpdateLeadBase(LeadInfo leadInfo)
        {
            ResResult resResult = new ResResult();
            try
            {
                if (leadInfo == null)
                {
                    log.Error("UpdateLeadBase 方法：传入对象为空");
                    return resResult.FailResult("LeadBll->UpdateLeadBase Error:传入对象为空 ");
                }
                if (Guid.Empty.Equals(leadInfo.leadid))
                {
                    log.Error("UpdateLeadBase 方法：对象id为空");
                    return resResult.FailResult("LeadBll->UpdateLeadBase Error:对象id为空 ");
                }
                if (string.IsNullOrWhiteSpace(leadInfo.lastname))
                {
                    log.Error("UpdateLeadBase 方法：客户姓名为空");
                    return resResult.FailResult("LeadBll->UpdateLeadBase Error:客户姓名为空 ");
                }

                //添加客户信息
                Entity entity = leadInfo.AsCrmEntity();
                //添加客户信息
                
                commonWcf.UpdateEntityById(entity);
                
                return resResult.SuccessResult(leadInfo.leadid);
            }
            catch (Exception ex)
            {
                log.Error("UpdateLeadBase方法 :" + ex.Message);
                throw ex;
                //return resResult.FailResult("LeadBll->UpdateLeadBase Error: " + ex.Message);
            }

        }

        /// <summary>
        /// 社区筛查团队模式修改
        /// 原程序 ：ScreenInfoServiceImpl-> modSQSC(DoctorUser user, TLeadBase tLeadBase, TScCustomer tScCustomer, List<TScResult> insertResults, List<TScResult> modifyResults, TScPreach tScPreach, ReservationInfo reservationInfo)
        /// </summary>
        /// <param name="sqsc">社区筛查单人模式对像</param>
        /// <returns></returns>
        public ResResult UpdateSQSCGroup(SCOBJ sqsc)
        {
            try
            {
                //1、更新潜客
                LeadInfo lead = sqsc.lead;
                //lead.new_patientsource = 3;
                resResult = UpdateLeadBase(lead);

                //2、更新筛查客户信息
                ScreenCustomer customer = sqsc.customer;
                //resResult = screenCustomerBll.UpdateScreenCustomer(customer);
                resResult = screenCustomerBll.UpdateScreenCustomerByAdmin(customer);
                //3、删除筛查结果 创建筛查结果 
                IEnumerable<ScreenResult> createResult = sqsc.CreateResults;
                if (createResult != null && createResult.Count() > 0)
                {
                    foreach (var sr in createResult)
                    {
                        screenResultBll.DeleteScreenResultByContentId(sr.new_categoryid, sr.new_itemid, sr.new_contentid, customer.new_customerid.ToString(), customer.new_scid.ToString());
                        sr.new_scid = customer.new_scid;
                        sr.new_customerid = customer.new_customerid;
                        sr.new_doctorid = lead.userid;
                    }

                    resResult = screenResultBll.MutipleCreateResult(createResult);
                }



                //4、创建或更新预约
                if (resResult.ResultState == 1 && sqsc.reservation != null)
                {
                    Reservation reservation = sqsc.reservation;

                    reservation.new_gender = lead.new_gender;
                    reservation.new_mobile = lead.address1_telephone1;
                    reservation.new_lead = lead.leadid;
                    reservation.new_age = lead.new_age;
                    reservation.new_new_screenitem = customer.new_scitemid;
                    reservation.new_insurancetype = lead.new_insurancetype;
                    reservation.new_insuranceid = lead.new_insuranceid;
                    reservation.new_screen = customer.new_scid;
                    reservation.new_source = lead.new_patientsource;
                    //if (reservation.new_reservationdate != null && reservation.new_hospital != null && reservation.new_department != null)
                    //2020-4-16 判断已经存在预约的逻辑增加预约项目的字段
                    if (reservation.new_reservationdate != null && reservation.new_hospital != null && reservation.new_department != null && reservation.new_contnt != null)
                    {
                        reservation.new_isreview = true;
                        DateTime startDate = reservation.new_reservationdate.Value.ToUniversalTime();
                        DateTime endDate = Convert.ToDateTime(reservation.new_reservationdate.Value.ToString("yyyy-MM-dd 15:59:59"));
                        //2020-4-16 判断已经存在预约的逻辑增加预约项目的字段
                        //Guid reservationid  = reservationBll.QueryReservationId(customer.new_customerid.Value, startDate, endDate, reservation.new_hospital.Value, reservation.new_department.Value);
                        Guid reservationid = reservationBll.CheckExistsReservation(customer.new_customerid.Value, startDate, endDate, reservation.new_hospital.Value, reservation.new_department.Value, reservation.new_contnt.Value);
                       
                        if (reservationid ==Guid.Empty)
                            reservationBll.CreateReservation(reservation);
                        else 
                        {
                            reservation.new_reservationid = reservationid;
                            Entity entityReservation = reservation.AsCrmEntity();
                           
                            CommonUtil.RemoveEntityAttributes(entityReservation, new string[] {
                                "new_age","new_insuranceid","new_reservationid","new_gender","new_mobile","new_insurancetype","new_remark"
                            });
                            commonWcf.UpdateEntityById(entityReservation);
                        }
                    }
             
                }

                return resResult.SuccessResult("CommonBll->UpdateSQSC : 成功");
            }
            catch (Exception ex)
            {
                log.Error("CommonBll-> UpdateSQSC :" + ex.Message);
                return resResult.FailResult("CommonBll-> UpdateSQSC :" + ex.Message);
            }
        }

        /// <summary>
        /// 社区筛查单人模式录入
        /// 原程序：ScreenInfoServiceImpl-> addSQSC(DoctorUser user, TLeadBase tLeadBase, TScCustomer tScCustomer, List TScResult  tScResults, TScPreach tScPreach, ReservationInfo reservationInfo)
        /// </summary>
        /// <param name="sqsc">社区筛查单人模式对像</param>
        /// <returns></returns>
        public ResResult CreateSQSC(CreateSCOBJ sqsc, UserInfo userInfo)
        {
            ResResult result = null;
            try
            {
                log.Error("1");
                //1、更新潜在客户
                sqsc.lead.ownerid = sqsc.propaganda.new_followdoctor.Value;
                sqsc.lead.new_inputingtime = DateTime.Now;
                //sqsc.lead.new_patientsource = 3;    //来自社区
                //sqsc.lead.new_datasource = 9;   //来自移动端
                Guid leadId = leadBll.QueryLeadidByConditions(sqsc.lead.lastname, sqsc.lead.ownerid, sqsc.lead.new_citizenid, sqsc.lead.address1_telephone1, sqsc.lead.telephone2);
                if (leadId != Guid.Empty) { sqsc.lead.leadid = leadId; }
                //if (sqsc.lead.new_birthdate.HasValue)
                //{
                //    sqsc.lead.new_birthdate = sqsc.lead.new_birthdate.Value.AddHours(8);
                //}
                result = !leadId.Equals(Guid.Empty) ? leadBll.UpdateLeadBase(sqsc.lead) : leadBll.SaveLeadInfo(sqsc.lead);
                leadId = result.Result;
                log.Error("2");
                //2、新增筛查客户
                ScreenCustomer customer = sqsc.customer;
                //customer.new_scstate = 0;
                customer.OwnerId = sqsc.lead.ownerid;
                customer.new_scnum = sequenceBll.GetSCNum();
                customer.new_customerid = leadId.Equals(Guid.Empty) ? result.Result : leadId;
                bool exists = screenCustomerBll.ExistsScreenCustomer(customer.new_customerid.Value, customer.new_scid.Value);
                if (!exists)
                {
                    customer.new_scstate = 1;
                    result = screenCustomerBll.CreateCustomer(customer);
                }

                if (leadId != Guid.Empty)
                {
                    foreach (ScreenResult screenResult in sqsc.CreateResults)
                    {
                        screenResult.new_customerid = leadId;
                    }
                }
                log.Error("3");
                //3、批量创建筛查结果
                if (sqsc.CreateResults != null && sqsc.CreateResults.Count() > 0)
                {
                    IEnumerable<ScreenResult> createResults = sqsc.CreateResults;
                    result = screenResultBll.MutipleCreateResult(createResults);
                    

                    // result = commonWcf.ExecultMutipleCreate(createResults);
                    //4、创建宣教

                    ////是否跟进为 否 查询当前用户所在的医院是否有筛查负责人，存在筛查负责人 则创建宣教，并且是否跟进选项为筛查负责人跟进,跟进负责人为该当前用户所在的医院筛查负责人，不存在筛查负责人则不创建宣教记录
                    //if (screenPropaganda.new_isfollowself.Value == 1)
                    //{
                    //    //Guid hospitalId = reservation.new_hospital.Value;
                    //    HospitalView hospitalView = hospitalBll.GetHospitalById(userInfo.siteid);
                    //    //否：查询当前用户所在医院的筛查负责人是否存在，不存在则不创建宣教，存在则创建宣教并赋相应的值
                    //    if (hospitalView.new_screenmanager.HasValue)
                    //    {
                    //        screenPropaganda.new_isfollowself = 2;
                    //        screenPropaganda.new_followdoctor = hospitalView.new_screenmanager;
                    //        result = screenPropagandaBll.CreatePropaganda(screenPropaganda);
                    //        leadBll.UpdateLeadBase(leadinfo);
                    //    }
                    //    //同一人，同一天，同一医院，同一科室不能有多次预约
                    //    if (reservation != null)
                    //    {
                    //        DateTime startDate = reservation.new_reservationdate.Value.ToUniversalTime();
                    //        DateTime endDate = Convert.ToDateTime(reservation.new_reservationdate.Value.ToString("yyyy-MM-dd 15:59:59"));
                    //        int isExists = reservationBll.QueryReservationBy(screenPropaganda.new_lead.Value, startDate, endDate, reservation.new_hospital.Value, reservation.new_department.Value);
                    //        if (isExists == 0)
                    //        {
                    //            resResult = reservationBll.CreateReservation(reservation);
                    //        }

                    //    }
                    //}
                    ////是否跟进为 是 则创建宣教 是否跟进选项为筛查组长跟进,跟进负责人为该当前活动负责人组长
                    //else
                    //{
                    //    screenPropaganda.new_isfollowself = 1;
                    //    result = screenPropagandaBll.CreatePropaganda(screenPropaganda);
                    //    leadBll.UpdateLeadBase(leadinfo);
                    //    //同一人，同一天，同一医院，同一科室不能有多次预约
                    //    if (reservation != null)
                    //    {
                    //        reservation.new_contnt = lead.new_disease;
                    //        DateTime startDate = reservation.new_reservationdate.Value.ToUniversalTime();
                    //        DateTime endDate = Convert.ToDateTime(reservation.new_reservationdate.Value.ToString("yyyy-MM-dd 15:59:59"));
                    //        int isExists = reservationBll.QueryReservationBy(screenPropaganda.new_lead.Value, startDate, endDate, reservation.new_hospital.Value, reservation.new_department.Value);
                    //        if (isExists == 0) result = reservationBll.CreateReservation(reservation);
                    //    }
                    //}
                    ScreenPropaganda propaganda = sqsc.propaganda;
                    if (sqsc.propaganda.new_isfollowself == 1) //跟踪进未否
                    {
                        HospitalView hospitalView = hospitalBll.GetHospitalById(userInfo.siteid);
                        if (hospitalView.new_screenmanager.HasValue)
                        {
                            propaganda.new_isfollowself = 2;
                            propaganda.new_lead = customer.new_customerid;
                            propaganda.new_followdoctor = hospitalView.new_screenmanager;
                            result = screenPropagandaBll.CreatePropaganda(propaganda);
                        }
                    }
                    else //根据为是 
                    {
                        //ScreenPropaganda propaganda = sqsc.propaganda;
                        propaganda.new_isfollowself = 1;
                        propaganda.new_lead = customer.new_customerid;
                        propaganda.OwnerId = sqsc.lead.ownerid;
                        result = screenPropagandaBll.CreatePropaganda(propaganda);
                    }



                    //ScreenPropaganda propaganda = sqsc.propaganda;
                    //propaganda.new_lead = customer.new_customerid;
                    //propaganda.OwnerId = sqsc.lead.ownerid;

                    //result = screenPropagandaBll.CreatePropaganda(propaganda);
                }
                log.Error("4");
                //5、创建预约
                if (result.ResultState == 1 && sqsc.propaganda.new_isorder.Value)
                {
                    sqsc.reservation.ownerId = sqsc.lead.ownerid;
                    sqsc.reservation.userid = sqsc.lead.userid;
                    sqsc.reservation.new_lead = leadId;
                    sqsc.reservation.new_source = sqsc.lead.new_patientsource;

                    result = reservationBll.CreateReservation(sqsc.reservation);
                }

                return result.SuccessResult(sqsc);
            }
            catch (Exception ex)
            {
                result = new ResResult();
                log.Error("CommonBll-> CreateSQSC :" + ex.Message+ex.StackTrace);
                return result.FailResult("CommonBll-> CreateSQSC : 错误," + ex.Message);
            }
        }

        /// <summary>
        /// 创建教宣
        /// </summary>
        /// <param name="spobj"></param>
        /// <returns></returns>
        public ResResult CreatePropagandaAndReservation(ScreenPropagandaOBJ spobj, UserInfo userInfo)
        {
            ResResult result = new ResResult();
            try
            {
                var lead = leadBll.QueryLeadInfoById(spobj.propaganda.new_lead.Value);
                ScreenPropaganda screenPropaganda = GetPropaganda(spobj, lead, userInfo);
                Reservation reservation = GetReservation(spobj, lead, userInfo);
                ScreenCustomer screenCustomer = GetCustomer(spobj, userInfo);
                LeadInfo leadinfo = spobj.lead;
                Entity leadEntity = leadinfo.AsCrmEntity();
                string[] attrNames = new string[]
                {
                    "leadid" ,"new_insurancetype","new_insurancelocation","description"
                };
                CommonUtil.RemoveEntityAttributes(leadEntity, attrNames);
                //leadinfo.userid = userInfo.userid;
                //是否跟进为 否 查询当前用户所在的医院是否有筛查负责人，存在筛查负责人 则创建宣教，并且是否跟进选项为筛查负责人跟进,跟进负责人为该当前用户所在的医院筛查负责人，不存在筛查负责人则不创建宣教记录
                if (screenPropaganda.new_isfollowself.Value == 1)
                {
                    //Guid hospitalId = reservation.new_hospital.Value;
                    HospitalView hospitalView = hospitalBll.GetHospitalById(userInfo.siteid);
                    //否：查询当前用户所在医院的筛查负责人是否存在，不存在则不创建宣教，存在则创建宣教并赋相应的值
                    if (hospitalView.new_screenmanager.HasValue)
                    {
                        screenPropaganda.new_isfollowself = 2;
                        screenPropaganda.new_followdoctor = hospitalView.new_screenmanager;
                        result = screenPropagandaBll.CreatePropaganda(screenPropaganda);

                        //leadBll.UpdateLeadBase(leadinfo);
                    }
                    //同一人，同一天，同一医院，同一科室不能有多次预约
                    if (reservation != null)
                    {
                        DateTime startDate = reservation.new_reservationdate.Value.ToUniversalTime();
                        DateTime endDate = Convert.ToDateTime(reservation.new_reservationdate.Value.ToString("yyyy-MM-dd 15:59:59"));
                        //增加同一个项目的判断 2020/4/16
                        //int isExists = reservationBll.QueryReservationBy(screenPropaganda.new_lead.Value, startDate, endDate, reservation.new_hospital.Value, reservation.new_department.Value);
                        Guid reserId = reservationBll.CheckExistsReservation(screenPropaganda.new_lead.Value, startDate, endDate, reservation.new_hospital.Value, reservation.new_department.Value,reservation.new_contnt.Value);
                        //if (isExists == 0)
                        if(reserId==Guid.Empty)
                        {
                            resResult = reservationBll.CreateReservation(reservation);
                        }

                    }
                    commonWcf.UpdateEntityById(leadEntity);
                    //commonWcf.UpdateEntityProxyById(userInfo.userid, leadEntity);
                }
                //是否跟进为 是 则创建宣教 是否跟进选项为筛查组长跟进,跟进负责人为该当前活动负责人组长
                else
                {
                    screenPropaganda.new_isfollowself = 1;
                    result = screenPropagandaBll.CreatePropaganda(screenPropaganda);
                    commonWcf.UpdateEntityById(leadEntity);
                    //commonWcf.UpdateEntityProxyById(userInfo.userid, leadEntity);
                    //leadBll.UpdateLeadBase(leadinfo);
                    //同一人，同一天，同一医院，同一科室不能有多次预约
                    if (reservation != null)
                    {
                        if(reservation.new_contnt==null)
                            reservation.new_contnt = lead.new_disease;
                        DateTime startDate = reservation.new_reservationdate.Value.ToUniversalTime();
                        DateTime endDate = Convert.ToDateTime(reservation.new_reservationdate.Value.ToString("yyyy-MM-dd 15:59:59"));
                        //int isExists = reservationBll.QueryReservationBy(screenPropaganda.new_lead.Value, startDate, endDate, reservation.new_hospital.Value, reservation.new_department.Value);
                        //if (isExists == 0) result = reservationBll.CreateReservation(reservation);
                        //增加同一个项目的判断 2020/4/16
                        Guid reserId = reservationBll.CheckExistsReservation(screenPropaganda.new_lead.Value, startDate, endDate, reservation.new_hospital.Value, reservation.new_department.Value, reservation.new_contnt.Value);
                        if (reserId == Guid.Empty)
                            resResult = reservationBll.CreateReservation(reservation);
                    }
                }
                var screenCustomerEntity = screenCustomer.AsCrmEntity();
                CommonUtil.RetainEntityAttributes(screenCustomerEntity, new string[] { "new_scnum" });
                //commonWcf.UpdateEntityProxyById(userInfo.userid, screenCustomerEntity);
                commonWcf.UpdateEntityById(screenCustomerEntity);
                //result = screenCustomerBll.UpdateScreenCustomer(screenCustomer);
                return result;
            }
            catch (Exception ex)
            {
                result = new ResResult();
                log.Error("CommonBll-> CreatePropagandaAndReservation :" + ex.Message);
                return result.FailResult("CommonBll-> CreatePropagandaAndReservation : 错误," + ex.Message);
            }
        }


        /// <summary>
        /// 获取筛查客户
        /// </summary>
        /// <param name="spobj"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        private ScreenCustomer GetCustomer(ScreenPropagandaOBJ spobj, UserInfo userInfo)
        {
            ScreenCustomer screenCustomer = spobj.customer;
            screenCustomer.userid = userInfo.userid;
            screenCustomer.new_scstate = 1;
            return screenCustomer;
        }

        /// <summary>
        /// 获取预约实体
        /// </summary>
        /// <param name="spobj"></param>
        /// <param name="lead"></param>
        /// <returns></returns>
        private Reservation GetReservation(ScreenPropagandaOBJ spobj, LeadView lead, UserInfo userInfo)
        {
            Reservation reservation = null;
            if (spobj.reservation != null)
            {
                reservation = spobj.reservation;
                reservation.userid = userInfo.userid;
                reservation.ownerId = spobj.propaganda.OwnerId;
                if (!string.IsNullOrWhiteSpace(lead.new_phone))
                {
                    reservation.new_mobile = lead.new_phone;
                }
                if (lead.new_gender != null)
                {
                    reservation.new_gender = lead.new_gender;
                }
                if (lead.new_age != null)
                {
                    reservation.new_age = lead.new_age;
                }
                if (!string.IsNullOrWhiteSpace(lead.new_wechat))
                {
                    reservation.new_wechat = lead.new_wechat;
                }
                if (!string.IsNullOrWhiteSpace(lead.new_qq))
                {
                    reservation.new_qq = lead.new_qq;
                }
            }
            return reservation;
        }

        /// <summary>
        /// 获取宣教实体
        /// </summary>
        /// <param name="spobj"></param>
        /// <param name="lead"></param>
        /// <returns></returns>
        private ScreenPropaganda GetPropaganda(ScreenPropagandaOBJ spobj, LeadView lead, UserInfo userInfo)
        {
            ScreenPropaganda screenPropaganda = spobj.propaganda;
            screenPropaganda.userid = userInfo.userid;
            if (lead.new_gender != null)
            {
                screenPropaganda.new_gender = lead.new_gender;
            }
            if (lead.new_age != null)
            {
                screenPropaganda.new_age = lead.new_age;
            }
            if (!string.IsNullOrWhiteSpace(lead.new_mobile))
            {
                screenPropaganda.new_mobile = lead.new_mobile;
            }
            if (!string.IsNullOrWhiteSpace(lead.Telephone1))
            {
                screenPropaganda.new_tel = lead.Telephone1;
            }

            return screenPropaganda;
        }
    }
}
